package com.patterns.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 反序列化方式破解单例模式
 * 需要单例类实现序列化
 * @author huangke
 *
 */
public class DeserializeSingleton {
	public static void main(String[] args) throws Exception{
		
		// >> 将对象序列化到硬盘 
		FileOutputStream fos = new FileOutputStream("d:/test.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		SingletonTemp temp1 = SingletonTemp.getInstance();
		oos.writeObject(temp1);
		oos.close();
		fos.close();
		
		// >> 将序列化的对象反序列化
		FileInputStream fis = new FileInputStream("d:/test.txt");
		ObjectInputStream ois = new ObjectInputStream(fis);
		SingletonTemp temp2 = (SingletonTemp) ois.readObject();
		
		System.out.println(temp1 == temp2); // >> false
	}
}

class SingletonTemp implements Serializable{
	private static SingletonTemp instance = new SingletonTemp();
	
	private SingletonTemp(){
	}
	
	public static SingletonTemp getInstance(){
		return instance;
	}
	
	// >> 反序列化时，如果定义了此方法，则会调用返回此方法对象,防止反序列化对象单例模式返回新的对象
//	private Object readResolve() {
//		return instance;
//	}
}
